﻿using MediatR;
using SmartCity.ProcessEngine.API.Domain;
using SmartCity.ProcessEngine.API.ErrorCode;
using SmartCity.ProcessEngine.API.Infrastructrue.Extensions;
using SmartCity.ProcessEngine.API.Infrastructrue.Interfaces;
using SmartCity.ProcessEngine.API.Write.Applications.Commands;

namespace SmartCity.ProcessEngine.API.Write.Applications.CommandHandlers
{
    /// <summary>
    ///表单分类请求添加命令
    /// </summary>
    public class FromTypeCreatedCommandHandler : IRequestHandler<FromTypeCreatedCommand, APIResult<int>>
    {
        /// <summary>
        /// 分类仓储
        /// </summary>
        private readonly IBaseRespository<WF_FromType> typeRep;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="typeRep">分类仓储</param>
        public FromTypeCreatedCommandHandler(IBaseRespository<WF_FromType> typeRep)
        {
            this.typeRep = typeRep;
        }
        /// <summary>
        /// 请求处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回任务</returns>
        public async Task<APIResult<int>> Handle(FromTypeCreatedCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result=new APIResult<int>();
            result.Code=APIResultCode.AddSuccess;
            result.Message=APIResultCode.AddSuccess.GetDescription();

            int num = 1;
            
            //查到最大的值
            var temp = typeRep.GetAll().OrderByDescending(x => x.TypeNo).FirstOrDefault();
            if (temp != null)
            {
                num = Convert.ToInt32(temp.TypeNo.Replace("T", " "))+1;
            }
            WF_FromType type=new WF_FromType();
            type.TypeNo = num.ToString().PadLeft(3,'0');
            type.IndustryId=request.IndustryId;
            type.TypeName=request.TypeName;
            await typeRep.AddAsync(type);

            return await Task.FromResult(result);
        }
    }
}
